<template>
  <div class="page-container">
    <div class="content-wrapper">
      <!-- 头像区域 -->
      <div class="avatar-section">
        <el-upload
          class="avatar-uploader"
          :action="uploadFileAction"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :headers="uploadHeaders"
        >
          <img v-if="user.avatar" :src="user.avatar" class="avatar"/>
          <i v-else class="el-icon-plus avatar-placeholder"></i>
        </el-upload>
        <div class="avatar-tip">点击更换头像（限制 JPG/PNG，最大 5MB）</div>
      </div>

      <!-- 用户信息表单 -->
      <el-form :model="user" label-width="120px" class="user-form">
        <el-form-item label="账户">
          <el-input v-model="user.account" disabled></el-input>
          <div v-if="user.account" class="field-tip">修改账户请前往安全中心</div>
          <div v-else class="field-tip-warn">请前往安全中心设置账户</div>
        </el-form-item>

        <el-form-item label="密码">
          <el-input type="password" v-model="password" disabled></el-input>
          <div class="field-tip">修改密码请前往安全中心</div>
        </el-form-item>

        <el-form-item label="邮箱">
          <el-input v-model="user.email" disabled></el-input>
          <div v-if="user.email" class="field-tip">修改邮箱请前往安全中心</div>
          <div v-else class="field-tip-warn">请前往安全中心设置邮箱</div>
        </el-form-item>

        <el-form-item label="手机号">
          <el-input v-model="user.phone" disabled></el-input>
          <div v-if="user.phone" class="field-tip">修改手机号请前往安全中心</div>
          <div v-else class="field-tip-warn">请前往安全中心设置手机号</div>
        </el-form-item>

        <el-form-item label="昵称">
          <el-input v-model="user.nickname" maxlength="255" show-word-limit></el-input>
        </el-form-item>

        <el-form-item label="姓名">
          <el-input v-model="user.name" maxlength="15" show-word-limit></el-input>
        </el-form-item>

        <el-form-item label="性别">
          <el-radio-group v-model="user.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
            <el-radio label="其他">其他</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="出生日期">
          <el-date-picker
            v-model="user.birth"
            type="date"
            placeholder="选择日期"
            format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="格言">
          <el-input v-model="user.motto" maxlength="30" show-word-limit></el-input>
        </el-form-item>

        <el-form-item label="简介">
          <el-input
            type="textarea"
            v-model="user.introduction"
            :rows="3"
            maxlength="500"
            show-word-limit
          ></el-input>
        </el-form-item>

        <el-form-item label="地址">
          <el-input
            type="textarea"
            v-model="user.address"
            :rows="2"
            maxlength="200"
            show-word-limit
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="saveUser">保存信息</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { getInfo, updateMeInfo } from '@/api/user'
import RsaUtil from '@/utils/rsa-util'
import { getToken } from '@/utils/auth'

export default {
  data() {
    return {
      uploadFileAction: `${process.env.VUE_APP_AUTH_HOST}/authService/authUser/v2/upload/avatar`,
      uploadHeaders: {
        Authorization: 'Bearer ' + getToken()
      },
      password: '********',
      user: {}
    }
  },
  created() {
    this.getSelfInfo()
  },
  methods: {
    beforeAvatarUpload(file) {
      const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isJPGorPNG) {
        this.$notify.error({
          title: '错误的格式',
          message: '头像只能是 JPG/PNG 格式!',
          showClose: false
        })
      }
      if (!isLt5M) this.$notify.error({ title: '文件过大', message: '上传文件不能超过 5MB!', showClose: false })
      return isJPGorPNG && isLt5M
    },
    async handleAvatarSuccess(res) {
      if (res.success) {
        this.$notify.success({ title: '修改结果', message: '头像更新成功！', showClose: false })
        await this.getSelfInfo()
        this.$store.commit('user/SET_USERINFO', this.user)
      } else {
        this.$notify.error({ title: '修改结果', message: '头像更新失败！', showClose: false })
      }
    },
    saveUser() {
      const rules = {
        name: 15,
        nickname: 255,
        motto: 30,
        introduction: 500, // 自定义
        address: 200       // 自定义
      }
      for (const field in rules) {
        if (this.user[field] && this.user[field].length > rules[field]) {
          this.$notify.error({
            title: '输入错误',
            message: `${field} 超过最大长度限制（${rules[field]}字符）`,
            showClose: false
          })
          return
        }
      }

      updateMeInfo(this.user).then(response => {
        this.$notify.success({ title: '修改结果', message: '保存成功', showClose: false })
        this.getSelfInfo()
      })
    },
    async getSelfInfo() {
      const { publicKey, privateKey } = RsaUtil.generateKeyPair()
      const rsa = new RsaUtil(publicKey, privateKey)
      getInfo({ publicKey: publicKey }).then(response => {
        this.user = response
        this.user.avatar = `${process.env.VUE_APP_BASE_HOST}/${this.user.avatar}`
        this.user.phone = rsa.decrypt(this.user.phone)
      })
    }
  }
}
</script>

<style scoped>
.page-container {
  display: flex;
  align-items: flex-start; /* 顶部开始布局 */
  justify-content: center; /* 水平方向居中 */
  height: calc(100vh - 100px);
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
  background-color: #ffffff;
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  overflow: hidden; /* 防止整体滚动 */
}

.content-wrapper {
  width: 100%;
  max-width: 700px;
  height: 100%;
  overflow-y: auto; /* 内部滚动 */
  padding-right: 10px; /* 给滚动条留空间 */
}

/* 头像样式 */
.avatar-section {
  text-align: center;
  margin-bottom: 30px;
}

.avatar-uploader {
  display: inline-block;
  width: 120px;
  height: 120px;
  border-radius: 50%;
  overflow: hidden;
  cursor: pointer;
  position: relative;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  font-size: 48px;
  color: #0084ff;
  line-height: 120px;
}

.avatar-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #999;
}

/* 表单样式 */
.user-form .el-form-item {
  margin-bottom: 20px;
}

.field-tip {
  font-size: 12px;
  color: #0084ff;
  margin-top: 4px;
}

.field-tip-warn {
  font-size: 12px;
  color: #d66500;
  margin-top: 4px;
}

/* 滚动条美化（可选） */
.content-wrapper::-webkit-scrollbar {
  width: 6px;
}

.content-wrapper::-webkit-scrollbar-thumb {
  background-color: rgba(0,0,0,0.2);
  border-radius: 3px;
}

.content-wrapper::-webkit-scrollbar-track {
  background-color: transparent;
}
</style>
